<?php
namespace appin\cms\controller;

use app\common\exception\AdminException;
use appin\cms\model\Articles;
use appin\cms\model\Column;
use appin\cms\WebController;

class Index extends WebController
{
    protected $page = 1;
    protected $limit = 10;

    /**
     *
     */
    public function initialize()
    {
        parent::initialize();
        $this->page = $this->request->param('page', 1, 'intval');
        $this->limit = $this->request->param('limit', 10, 'intval');
    }

    /**
     * 栏目管理
     * @return \think\response\View
     * @throws AdminException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $alias = $this->request->param('alias', 'index');
        $column = '';

        if ( is_numeric($alias) ) {
            $column = Column::withoutGlobalScope()->find($alias);
        } else if(!empty($alias)){
            $column = Column::withoutGlobalScope()->where('alias', $alias)->find();
        }

        if (!$column) {
            throw new AdminException('栏目不存在,将别名设置为index则成为首页');
        }

        if ( isset($column['href']) && !empty($column['href']) ) {
            return redirect($column['href']);
        }

        $template = 'index';
        $mode = 'pages';
        if ($column) {
            if (!empty($column['template'])) {
                $template = $column['template'];
            } else {
                $template = $column['mode'];
            }
            $mode = $column['mode'];
        }

        return $this->render($template, [
            'column' => $column,
            'data' => $this->modeData($mode, $this->limit),
            'column_id' => $column['id']
        ]);
    }

    /**
     * 获取数据
     * @param $mode
     * @param int $limit
     * @param string $where
     * @return array
     */
    private function modeData($mode, $limit = 10, $where = '')
    {
        $data = [];
        switch($mode) {
            case 'articles':
                $data = Articles::UseWhere($where)->order('sort desc,id desc')->paginate($limit);
                break;
        }
        return $data;
    }

    /**
     * 文章详情
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function detail()
    {
        $id = $this->request->param('id', 0, 'intval');
        $detail = Articles::find($id);
        return $this->render('', ['detail' => $detail, 'column_id' => $detail['column_id']]);
    }
}